package org.example.service.impl;

import org.example.mapper.GoodMapper;
import org.example.mapper.OrderMapper;
import org.example.pojo.Good;
import org.example.pojo.Order;
import org.example.pojo.Result;
import org.example.service.OrderService;
import org.example.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;

@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private GoodMapper goodMapper;

    @Override
    @Transactional
    public Result createOrder(Long goodId) {
        //1、查询商品
        Good good = goodMapper.selectForUpdate(goodId);
        //2、判断库存够不够
        if(good.getStock() == 0) {
            return Result.error("库存不足");
        }
        //3、更新库存
        good.setStock(good.getStock() - 1);
        goodMapper.update(good);
        //4、创建订单
        Order order = new Order();
        order.setGoodId(goodId);
        Map<String,Object> map = ThreadLocalUtil.get();
        Integer userId = (Integer) map.get("id");
        order.setUserId(userId.longValue());
        orderMapper.insert(order);
        return Result.success(order);
    }
}
